import { defineStore } from "pinia"
import type { systemState } from "../type"
import { ElMessage } from "element-plus"
import {
  GetPageInfo,
  AddPageInfo,
  DeletePageData,
  EditPageInfo
} from "@/service/api"

export const systemStore = defineStore({
  //js命名
  id: "system",
  // 数据
  state: (): systemState => {
    return {
      menuInfo: [],
      menuPagination: {},
      permInfo: [],
      permPagination: {},
      roleInfo: [],
      rolePagination: {},
      userInfo: [],
      userPagination: {}
    }
  },
  // computed 修饰一些值
  getters: {
    tableData(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}Info`]
      }
    },
    getPagination(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}Pagination`]
      }
    }
  },
  // methods, 同步和异步都可以, 修改state
  actions: {
    // 获取页面信息
    async getPageInfo(payload: any) {
      // console.log(payload)
      const res: any = await GetPageInfo(payload.url, payload.queryInfo)
      const infoName = payload.url.replace("/", "") + "Info"
      const paginationName = payload.url.replace("/", "") + "Pagination"
      ;(this.$state as any)[infoName] = res.data
      ;(this.$state as any)[paginationName] = res.meta.pagination
      console.log(res.data)
    },
    // 删除信息
    async deletePageData(payload: any) {
      const url = `${payload.url}/${payload.id}`
      const res: any = await DeletePageData(url)
      // 重新请求数据
      this.getPageInfo({
        url: payload.url,
        queryInfo: {
          per_page: 20, // 每页的数据条数
          page: 1 // 当前页页码
        }
      })
      ElMessage.success(res.message)
    },
    // 新建信息
    async addPageInfo(payload: any) {
      // console.log(payload)
      const res: any = await AddPageInfo(payload.url, payload.newData)
      // 重新请求数据
      this.getPageInfo({
        url: payload.url,
        queryInfo: {
          per_page: 20, // 每页的数据条数
          page: 1 // 当前页页码
        }
      })
      ElMessage.success(res.message)
    },
    // 编辑信息
    async editPageInfo(payload: any) {
      const res: any = await EditPageInfo(
        payload.url + payload.id,
        payload.newData
      )
      // 重新请求数据
      this.getPageInfo({
        url: payload.url,
        queryInfo: {
          per_page: 20, // 每页的数据条数
          page: 1 // 当前页页码
        }
      })
      ElMessage.success(res.message)
    }
  }
})
